package com.ultra.netty.A020;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * JDK自带阻塞网络编程
 *
 * @author fan
 */
public class PlainOioServer {

    private static final Logger logger = LoggerFactory.getLogger(PlainOioServer.class);

    public void server(int port) throws IOException {
        final ServerSocket socket = new ServerSocket(port);
        for (; ; ) {
            final Socket clientSocket = socket.accept();
            logger.info("accepted connection from {}", clientSocket);
            new Thread(() -> {
                OutputStream out = null;
                try {
                    out = clientSocket.getOutputStream();
                    out.write("Hi!\r\n".getBytes(StandardCharsets.UTF_8));
                    out.flush();
                    clientSocket.close();
                } catch (IOException e) {
                    logger.error("", e);
                } finally {
                    try {
                        if (out != null) {
                            out.close();
                        }
                    } catch (IOException ignore) {
                    }
                }
            }).start();
        }
    }
}
